/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import { loadScript } from '@/utils/utils';
import { Cascader } from 'antd';
import type { SizeType } from 'antd/lib/config-provider/SizeContext';
import { isArray } from 'lodash';
import React, { CSSProperties, useEffect, useState } from 'react';

type CityCascaderType = 'all' | 'province' | 'city';
interface CityCascaderProps {
  size?: SizeType;
  onChange: (v: string[]) => void;
  placeholder?: string;
  type?: CityCascaderType;
  value: string[];
  allowClear?: boolean;
  style?: CSSProperties;
  disabled?: boolean;
}

interface AreaDataItem {
  value: string;
  label: string;
  children?: AreaDataItem[];
}
interface AreaDataListItem extends AreaDataItem {
  children?: AreaDataItem[];
}

interface AreaItem {
  id: string;
  pid: number;
  name: string;
}

let formattedAddressList: AreaDataListItem[] | null = null;
const CityCascader: React.FC<CityCascaderProps> = (props) => {
  const { onChange, value, size, type, allowClear, style, placeholder, disabled = false } = props;
  const [options, setOptions] = useState<AreaDataListItem[]>([]);

  const hasValue = value && !!value.filter((item) => !!item).length;

  // 格式化区域列表
  const formatAreaList = (area: AreaItem[][]) => {
    if (formattedAddressList) {
      setOptions(formattedAddressList);
      return;
    }
    if (!isArray(area)) return;

    const list: AreaDataListItem[] = [];
    const areaLen = area.length;
    const pIdIndex = {};
    const cIdIndex = {};
    const isProvince = type === 'province';
    const isCity = type === 'city';
    for (let p = 0; p < areaLen; p++) {
      const arr = (area[p] || []).filter((item: any) => !!item);
      const arrLen = arr.length;
      if (arrLen > 0) {
        for (let i = 0; i < arrLen; i++) {
          const { id, pid, name } = arr[i] || {};
          if (!name) continue;
          const data: AreaDataItem = {
            value: name,
            label: name,
          };
          if (p === 1 && 1 * pid === 0) {
            list.push(data);
            pIdIndex[id] = list.length - 1;
          } else if (p === 2) {
            // 市
            if (isProvince) {
              continue;
            }
            const parent: any = list[pIdIndex[pid]];
            parent.children = parent.children || [];
            parent.children.push(data);
            cIdIndex[id] = parent.children.length - 1;
          } else {
            // 区
            if (isProvince || isCity) {
              continue;
            }
            const currentCity = area[2][pid];
            if (!currentCity) continue;
            const cIndex = cIdIndex[pid];
            const pIndex = pIdIndex[currentCity.pid];
            const parent = list[pIndex].children![cIndex];
            parent.children = parent.children || [];
            parent.children.push(data);
          }
        }
      }
    }
    formattedAddressList = list;
    setOptions(list);
  };

  useEffect(() => {
    loadScript('https://cdn-static.judanke.cn/js/pho/min-areas.js?v=20221028').then(() => {
      formatAreaList(window.address);
    });
  }, []);

  const handleChange = (v: any[]) => onChange(v);

  const displayRender = (label: string[]) => {
    let index = -1;
    switch (type) {
      case 'province':
        index = 0;
        break;
      case 'city':
        index = 1;
        break;
      default:
        break;
    }
    if (hasValue) {
      const values = value || label;
      return values[index] || values.join('/');
    }
    return '';
  };

  return (
    <Cascader
      style={{ width: '100%', ...style }}
      displayRender={displayRender}
      value={hasValue ? value : []}
      size={size}
      notFoundContent='未匹配到对应区域'
      showSearch
      expandTrigger='hover'
      options={options}
      onChange={handleChange}
      placeholder={placeholder}
      allowClear={allowClear}
      autoFocus={false}
      disabled={disabled}
    />
  );
};

CityCascader.defaultProps = {
  size: 'middle',
  onChange: () => {},
  placeholder: '选择省市区',
  type: 'all',
};

export default CityCascader;
